<template>
  <div id="Books">
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="书籍名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入书籍名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['curriculumSystemManagement:book:add']"
          >新增教材
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="batchAddBook"
            v-hasPermi="['curriculumSystemManagement:book:add']"
          >json格式新增教材
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="bookList"
        row-key="deptId"
      >
        <el-table-column prop="name" label="教材名称"></el-table-column>
        <el-table-column prop="code" label="书籍编号"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-hasPermi="['curriculumSystemManagement:book:update']"
              @click="checkDetails(scope.row,'update')"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              v-hasPermi="['curriculumSystemManagement:book:look']"
              @click="checkDetails(scope.row,'look')"
            >查看
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-hasPermi="['curriculumSystemManagement:book:remove']"
              @click="removeBook(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改教材对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="close">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="教材编号" prop="isbn">
            <el-input v-model="form.isbn" placeholder="请输入教材编号" :disabled="!isAdd"/>
          </el-form-item>
          <el-form-item label="教材名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入教材名称" :disabled="!isEdit" />
          </el-form-item>
          <el-divider content-position="center">教材信息</el-divider>
          <div v-if="isAdd" class="promptStatement">章节信息请在先新增完教材后在进行添加</div>
          <el-form-item v-else label="章节数据">
            <el-tree ref="tree"
                     :data="treeData" :props="defaultProps"
                     node-key="code"
                     :expand-on-click-node="false">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <el-input v-if="data.isEdit" v-model="handleUpdateContent" size="mini"></el-input>
                <span v-else>{{ node.label }}</span>
                <span v-if="isEdit" style="float: right">
                  <el-button
                    v-if="afterCodeProcessor(data.code)"
                    type="text"
                    size="mini"
                    @click="() => addNode(node,data)"
                  >
                    新增子节点
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="() => updateNode(node,data)"
                  >
                    {{data.isEdit?'确认':'修改'}}
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="() => removeNode(node, data)"
                  >
                    删除
                  </el-button>
                </span>
              </span>
            </el-tree>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>


      <!-- 批量新增教材弹窗 -->
      <el-dialog title="json格式新增教材"  :visible.sync="batchOpen" width="600px" append-to-body>
        <el-form ref="jsonForm"
                 v-loading="jsonFormLoading"
                 label-position="top"
                 :model="jsonForm"
                 :rules="jsonFormrules"
                 label-width="80px">
          <el-form-item label="教材json数据" prop="json">
            <el-input type="textarea"
                      :autosize="{ minRows: 10, maxRows: 20}"
                      v-model="jsonForm.json" placeholder="请输入教材json数据"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :loading="jsonFormLoading" @click="jsonFormSubmitForm">确 定</el-button>
          <el-button @click="jsonFormCancel">取 消</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  addBookNode,
  bookDetail,
  deleteBookByNode,
  listBooks, textBookImport,
  updateBookNode
} from '@/api/curriculumSystemManagement/book'

export default {
  name: 'Dept',
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格数据
      bookList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开
      expand: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null
      },
      // 总条数
      total: 0,
      // 表单参数
      form: {
        isbn:'',
        name:'',
        data:undefined
      },
      // 表单校验
      rules: {
        code: [
          { required: true, message: '教材编号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '教材名称不能为空', trigger: 'blur' }
        ]
      },
      jsonFormrules:{
        json:[
          { required: true, message: '数据不能为空', trigger: 'blur' }
        ]
      },
      // 章节树数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      //是否编辑 ,true编辑,false,查看
      isEdit:false,
      handleUpdateContent:'默认名字',
      isAdd:false,
      //json格式新增教材弹窗状态
      batchOpen:false,
      //json格式新增教材表单
      jsonForm:{
        json:''
      },
      jsonFormLoading:false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** json格式新增教材表单提交*/
    jsonFormSubmitForm(){
      const self = this
      self.$refs['jsonForm'].validate(async valid => {
        if(valid){
          this.jsonFormLoading = true
          await textBookImport(self.jsonForm)
          this.jsonFormLoading = false
          this.batchOpen = false
          this.$message({
            type:'success',
            message:'新增成功'
          })
          await this.getList()
        }
      })
    },
    /** json格式新增教材表单取消按钮*/
    jsonFormCancel(){
      this.batchOpen = false
    },
    /** json格式新增教材按钮*/
    batchAddBook(){
      this.jsonForm = {json:''}
      this.batchOpen = true
    },
    /** 弹窗关闭回调*/
    close(){
      this.isAdd = false
    },
    /** 判断是否还可以新增子节点*/
    afterCodeProcessor(code){
      let tempCode = code.substring(code.length-6)
      //把字符串2个为一组拆分
      let tempCodeArray = []
      for (let i = 0 ; i <tempCode.length ; i++){
        let str
        if(i%2 == 0){
          str = tempCode[i] + tempCode[i+1]
          tempCodeArray.push(str)
        }
      }
      let lastNumber = Number(tempCodeArray[tempCodeArray.length-1])
      return lastNumber === 0
    },
    /** 新增子节点*/
    async addNode(node,data){
      this.handleUpdateContent = '默认名字'
      this.$refs.tree.store.nodesMap[data.code].expanded = true;
      let afterCode = this.calculateCode(data)
      let resultsCode = `${data.isbn}${afterCode.join('')}`
      // let tempParent = data.code.substring(data.code.length-6)
      // let tempVia = data.code.substring(data.via.length-6)
      const newChild = {
        code:resultsCode,
        isbn:data.isbn,
        name:'默认名字',
        isEdit:true,
        parent:data.code,
        via:`${data.via},${data.code}`
      }
      console.log(newChild)
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      const res = await addBookNode(newChild)
      data.children.push(newChild);
    },
    /** 计算新增的章、节的code*/
    calculateCode(data){
      let tempCode
      if(!data.children){
        //还没有子节点数据
        tempCode = data.code
        //获取code的后6位
        let afterCode = tempCode.substring(tempCode.length-6)
        //把字符串2个为一组拆分
        let tempCodeArray = []
        for (let i = 0 ; i <afterCode.length ; i++){
          let str
          if(i%2 == 0){
            str = afterCode[i] + afterCode[i+1]
            tempCodeArray.push(str)
          }
        }
        //找到第一个为0的数，并加1
        for (let i in tempCodeArray){
          let number = Number(tempCodeArray[i])
          if(number<=0){
            number++
            if(number<10){
              number = `0${number}`
            }
            tempCodeArray[i] = `${number}`
            break;
          }
        }
        return tempCodeArray
      }else{
        //已经有子节点数据
        tempCode = data.children[data.children.length-1].code
        //获取code的后6位
        let afterCode = tempCode.substring(tempCode.length-6)
        //把字符串2个为一组拆分
        let tempCodeArray = []
        for (let i = 0 ; i <afterCode.length ; i++){
          let str
          if(i%2 == 0){
            str = afterCode[i] + afterCode[i+1]
            tempCodeArray.push(str)
          }
        }
        for (let i = tempCodeArray.length-1 ; i>=0 ; i--){
          let number = Number(tempCodeArray[i])
          if(number>0){
            number++
            if(number<10){
              number = `0${number}`
            }
            tempCodeArray[i] = `${number}`
            break;
          }
        }
        return tempCodeArray
      }
    },
    /** 删除教材*/
    removeBook(data){
      this.$confirm(`此操作将永久教材${data.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let postData = {
          code:data.code,
          isbn:data.isbn
        }
        await deleteBookByNode(postData)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.open = false
        await this.getList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /** 编辑节点*/
    async updateNode(node,data){
      const self = this
      let tempCode = data.code
      if(!data.isEdit){
        self.handleUpdateContent = data.name
      }
      data.isEdit = !data.isEdit
      //内容修改了
      if(data.name !== self.handleUpdateContent){
        let postData = {
          code:tempCode,
          name:self.handleUpdateContent
        }
        await updateBookNode(postData)
        data.name = self.handleUpdateContent
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
      }
    },
    /** 删除节点*/
    removeNode(node,data){
      this.$confirm(`此操作将永久${data.name}及它的子节点, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let postData = {
          code:data.code,
          isbn:data.isbn
        }
        await deleteBookByNode(postData)
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.code === data.code);
        children.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /** 查询教材列表 */
    async getList() {
      this.loading = true
      const response = await listBooks(this.queryParams)
      this.bookList = response.rows
      this.total = response.total
      this.loading = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        isbn: undefined,
        name: undefined,
        data: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.isAdd = true
      this.isEdit = true
      this.open = true
      this.title = '添加教材'
    },
    /** 查看详情按钮*/
    async checkDetails(data,state) {
      const self = this
      switch (state) {
        case 'update':
          self.isEdit = true
          break;
        case 'look':
          self.isEdit = false
          break;
      }
      const response = await bookDetail(data.isbn)
      let List = self.handleTree(response.data, 'code', 'parent')
      self.treeData = List
      self.form.name = data.name
      self.form.isbn = data.isbn
      self.open = true
    },
    /** 提交按钮 */
    submitForm: function() {
      const self = this
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if(self.isAdd){
            //新增
            let postData = {
              code:`${self.form.isbn}000000`,
              isbn:self.form.isbn,
              name:self.form.name,
              description:'',
              parent:0,
              via:0
            }
            const res = await addBookNode(postData)
            self.$message({
              type:'success',
              message:res.msg
            })
            this.open = false
            await this.getList()
          }else{
            //修改
            let postData = {
              code:`${self.form.isbn}000000`,
              isbn:self.form.isbn,
              name:self.form.name,
              description:'',
              parent:0,
              via:0
            }
            const res = await updateBookNode(postData)
            self.$message({
              type:'success',
              message:res.msg
            })
            this.open = false
            await this.getList()
          }
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .custom-tree-node {
  width: 100%;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
::v-deep .el-input--mini .el-input__inner{
  height: 25px;
  line-height: 25px;
}
.promptStatement{
  text-align: center;
  color: #999999;
}
</style>
